from meta_service.utils import mkdir_if_not_exist
import os
import uuid
import shutil

CACHE_TOPIC_NAME = "tis.cache"

class TempFile:

    MAX_TRY_TIMES = 10

    def gen_unique_id(self):
        return str(uuid.uuid4())

    def __init__(self,file_dir:str) -> None:
        self.file_dir = file_dir
        for _ in range(self.MAX_TRY_TIMES):
            self.temp_filename = f"{self.gen_unique_id()}.tmp"
            self.file_path = os.path.join(self.file_dir,self.temp_filename)
            if os.path.exists(self.file_path) == False:
                os.makedirs(os.path.dirname(self.file_path),exist_ok=True)
                with open(self.file_path,"w") as fp:
                    fp.close()
                return
        raise Exception("create temp file failed")
    
    def FileName(self) -> str:
        return self.temp_filename


class IndexMeta:

    def __init__(self,tis_path:str,topic_name:str,index_name:str) -> None:
        self.tis_path = tis_path
        self.topic_name = topic_name
        self.index_name = index_name


def MoveIndex(src_meta:IndexMeta,dst_meta:IndexMeta) -> bool:
    src_index_path = os.path.join(
        src_meta.tis_path,
        src_meta.topic_name,
        src_meta.index_name
    )
    if not os.path.exists(src_index_path):
        return False
    dst_index_path = os.path.join(
        dst_meta.tis_path,
        dst_meta.topic_name,
        dst_meta.index_name
    )
    # move
    try:
        os.makedirs(os.path.dirname(dst_index_path), exist_ok=True)
        shutil.move(src_index_path, dst_index_path)
        return True
    except Exception as e:
        print(f"move index error: {e}")
    return False

